import { ref } from 'vue'
import { defineStore } from 'pinia'
import {getCategoryListApi, shopListApi, configApi} from '@/api'

export const useCommStore = defineStore('comm', () => {
  const config = ref({
    about_us:'',
    company_address: '',
    company_desc: '',
    company_mobile: '',
    web_site_copyright: ''
  })
  // 是否显示分类抽屉（仅在pc端显示）
  const isShowMenu = ref(false)
  // 店铺列表
  const shopList = ref('')
  // 选择的店铺 id
  const shopId = ref('')
  // 选中的店铺名称
  const shopName = ref('')
  // 分类列表
  const categoryList = ref([])
  // 选中的分类 id
  const categoryId = ref('')
  const categoryName = ref('')
  // 顶部搜索内容
  const search = ref('')
  const menuToggle = () =>{
    isShowMenu.value = !isShowMenu.value
  }
  const setCategoryId = (id, name) => {
    categoryId.value = id
    categoryName.value = name
  }
  const setSearch = (keyword) => {
    search.value = keyword
  }
  const setShopList = () => {
    shopListApi().then(res => {
      shopList.value = res.data
      if (!shopId.value) {
        shopId.value = shopList.value[0]?.id
        shopName.value = shopList.value[0].name
      }
    })
  }
  const setShopId = (id, name) => {
    shopId.value = id
    shopName.value = name
  }
  const getConfig = () => {
    configApi().then(res => {
      config.value = res
    })
  }
  const setCategoryList = () => {
    getCategoryListApi().then(res => {
      categoryList.value = res.data
      if (categoryList.value.length === 0) return
      categoryList.value.forEach((category) => {
        category.id = category?.id.toString()
        if (category?.children) {
          category.children.forEach(child => {
            child.id = child?.id.toString()
          })
        }
      })
    })
  }
  return {
    config,
    isShowMenu,
    shopList,
    shopId,
    shopName,
    categoryList,
    categoryId,
    categoryName,
    search,
    menuToggle,
    setShopList,
    setCategoryList,
    setCategoryId,
    setSearch,
    getConfig,
    setShopId
  }
},{
  persist: true
})